import axios from 'axios'
import type { AxiosInstance, AxiosResponse } from 'axios'


const isDev: boolean = process.env.NODE_ENV == 'development'



const request: AxiosInstance = axios.create({
    baseURL: isDev ? '/' : 'https://api.moonshot.cn/v1',   //http://162.14.108.31:3001/api
    timeout: 60000
})






request.interceptors.request.use(function (config: any) {
    config.headers['token'] = localStorage.getItem('token') || ''
    return config;
}, function (error: any) {
    return Promise.reject(error);
});



request.interceptors.response.use(function (response) {
    return response;
}, function (error: any) {
    return Promise.reject(error);
});


interface iConfig {
    url: string,
    method: string,
    data?: any
    headers?: any
}


export default function ajax(config: iConfig) {
    const { url = '', method = 'get', data = {}, headers = {} } = config
    switch (method.toUpperCase()) {
        case 'GET':
            return request.get(url, { params: data })
        case 'POST':
            if (headers['Content-Type'] == 'application/x-www-form-urlencoded') {
                const obj = new URLSearchParams()
                for (const key in data) {
                    obj.append(key, data[key])
                }
                return request.post(url, obj, { headers })
            }

            if (headers['Content-Type'] == 'multipart/form-data') {
                const obj = new FormData()
                for (const key in data) {
                    obj.append(key, data[key])
                }
                return request.post(url, obj, { headers })
            }
            return request.post(url, data)
        case 'DELETE':
            return request.delete(url, { data })
        case 'PUT':
            return request.put(url, data)
        case "PATCH":
            return request.patch(url, data)
        default:
            return request.request(config)
    }
}